package com.gitee.zhanyao.monomer.service.impl;

import com.gitee.zhanyao.monomer.entity.SysUser;
import com.gitee.zhanyao.monomer.model.RegisterModel;
import com.gitee.zhanyao.monomer.repository.SysUserRepository;
import com.gitee.zhanyao.monomer.service.SysUserService;
import com.gitee.zhanyao.monomer.util.datatables.DataTablesRequest;
import com.gitee.zhanyao.monomer.util.datatables.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public Page<SysUser> getUsers(DataTablesRequest<SysUser> dataTablesRequest) {
        Sort sort = PageUtil.getOrders(dataTablesRequest);
        Specification<SysUser> specification = getWhereClause(dataTablesRequest.getParams());
        Page<SysUser> all = sysUserRepository.findAll(specification, PageRequest.of(dataTablesRequest.getPage(),
                dataTablesRequest.getLength(), sort));
        return all;
    }

    @Override
    public String register(RegisterModel registerModel) throws Exception {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(registerModel, sysUser);
        sysUserRepository.save(sysUser);
        return sysUser.getId();
    }

    @Override
    public void deletion(String userId) throws Exception {
        sysUserRepository.deleteById(userId);
    }

    @Override
    public SysUser users(String userId) {
        return sysUserRepository.getOne(userId);
    }

    private Specification<SysUser> getWhereClause(SysUser params) {
        return new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> predicate = new ArrayList<>();

                Predicate[] pre = new Predicate[predicate.size()];
                return query.where(predicate.toArray(pre)).getRestriction();
            }
        };
    }

}
